package com.lifeng.security;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by lifeng on 2019/8/12.
 * 自定义权限不足的处理
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    private String errorPage;
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {

        if(isAjax(httpServletRequest)){
            httpServletResponse.getWriter().write("json");//输出json数据，而非页面跳转
        }else{
            //非ajax时跳转到系统默认是403 页面
            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN,e.getMessage());
            //也可以跳到自定义的错误页面url
        }
    }

    public boolean isAjax(HttpServletRequest httpServletRequest){
        //此处可以判断是否是ajax请求
        return false;
    }

    public String getErrorPage() {
        return errorPage;
    }

    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }
}
